package com.starblink.postvideo.ui

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.network.config.PostConfig.postRecommendPage
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.route.RoutePage
import com.starblink.rocketreserver.FetchPostsQuery
import com.starblink.rocketreserver.QueryContentDetailQuery
import com.starblink.rocketreserver.SearchHashtagPostQuery
import com.starblink.rocketreserver.SharePostMutation
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.type.HashtagPostParam
import com.starblink.rocketreserver.type.PostRecommendQueryParam
import kotlinx.coroutines.launch

class VideoDetailVM : BaseViewModel() {
    var resultList: MutableLiveData<ArrayList<PostD>> = MutableLiveData(arrayListOf())
    var idList: ArrayList<String> = arrayListOf()//已有详情的post内容
//    var fragmentList: MutableLiveData<ArrayList<Fragment>> = MutableLiveData()

    var originalPostId: String = ""//初始postId
    var isLoadingMore: Boolean = false
    var sceneId: String = ""//其它场景id
    var scenePageNo = 1

    /**
     * 获取内容详情
     */
    fun getPostDetail(postId: String, index: Int) {
        if (postId.isNotEmpty()) {
            idList.add(postId)
            viewModelScope.launch {
                val response = SkGqlClient.skQuery(
                    QueryContentDetailQuery(postId)
                )

                if (response?.data != null && response.data!!.queryContentDetail != null) {
                    var post = response.data!!.queryContentDetail!!.postD
//                    Log.d("VideoDetailVM", "---9-${post.posterInfo.poster.relationCode}")
                    if (resultList.value?.isNotEmpty() == true) {
                        if (index < resultList.value!!.size) {
//                            Log.d("VideoDetailVM", "---9-${post.posterInfo.poster.relationCode}")
                            resultList.value?.set(if (index > 0) index else 0, post)
                            resultList.value = resultList.value
                        }
                    } else {
                        resultList.value?.add(post)
                        resultList.value = resultList.value
                    }
                } else {
//                mList.value = arrayListOf()
                }
            }
        }
    }

    /**
     * 加载推荐数据
     */
    fun getRecommend(scene: Int) {
        isLoadingMore = true
        viewModelScope.launch {
            if (scene == RoutePage.Post.SCENE.TOPIC.value) {//获取话题列表
                val response = SkGqlClient.skQuery(
                    SearchHashtagPostQuery(
                        hashtagPostParam = HashtagPostParam(
                            hashtagId = Optional.present(sceneId),
                            postId = Optional.present(""),
                            pageNo = Optional.present(scenePageNo),
                            pageSize = Optional.present(20)
                        )
                    )
                )
                isLoadingMore = false
                if (response?.data != null && response.data!!.searchHashtagPost != null && response.data!!.searchHashtagPost!!.hashtagPostVOF != null) {
                    val hashtagPostVOF = response.data!!.searchHashtagPost!!.hashtagPostVOF
                    var list1 = hashtagPostVOF.posts
                    var list = arrayListOf<PostD>()
                    Log.d("VideoDetailVM", "---9-${list1}")
                    list1!!.forEach { e ->
                        if (e != null && e.postF.contentType == "2") {
                            list.add(e.postF.toJson().toBean())
                            var imgUrl = e.postF.mainPic
                            ImageUtils.preloadImage(commContext(), imgUrl)
                        }
                    }
                    Log.d("VideoDetailVM", "---9-${list}")
                    if (list.isNotEmpty()) {
                        scenePageNo++
                        resultList.value?.addAll(list)
                        resultList.value = resultList.value
                    }
                }
            } else {
                val response = SkGqlClient.skQuery(
                    FetchPostsQuery(
                        postParams = PostRecommendQueryParam(
                            1,
                            relatedPostId = Optional.Absent,
                            postRecommendPage,
                            20,
                            advertiseId = Optional.present(AppsflyerManager.getADID()),
                            clientTime = Optional.present(System.currentTimeMillis().toString()),
                            isReported = Optional.present(true),
                        ), isPostDetail = true
                    )

                )
                isLoadingMore = false
                if (response?.data != null && response.data!!.fetchRecommendPost != null) {
                    var postList = response.data!!.fetchRecommendPost
                    var list = arrayListOf<PostD>()
                    postList!!.forEach { e ->
                        var post = e.postD
                        post?.let {
                            if (post.contentType == "2") {//筛选图文类型
                                var imgUrl = post.mainPic
                                ImageUtils.preloadImage(commContext(), imgUrl)

                                list.add(post)
                            }
                            idList.add(post.id)
                        }
                    }
                    if (list.isNotEmpty()) {
                        postRecommendPage++
                        resultList.value?.addAll(list)
                        resultList.value = resultList.value
                    }
                }
            }
        }
    }

    fun sharePost(postId: String) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                SharePostMutation(postId)
            )
        }
    }

}